* Indent.
[lhc/web/wiklou.git] / includes / Image.php
1 <?php
2 /**
3 * @package MediaWiki
4 */
5
6 if ( $wgShowEXIF ) {
7 require_once ( 'exifReader.inc' ) ;
8 }
9
10 /**
11 * Class to represent an image
12 *
13 * Provides methods to retrieve paths (physical, logical, URL),
14 * to generate thumbnails or for uploading.
15 * @package MediaWiki
16 */
17 class Image
18 {
19 /**#@+
20 * @access private
21 */
22 var $name, # name of the image (constructor)
23 $imagePath, # Path of the image (loadFromXxx)
24 $url, # Image URL (accessor)
25 $title, # Title object for this image (constructor)
26 $fileExists, # does the image file exist on disk? (loadFromXxx)
27 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
28 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
29 $historyRes, # result of the query for the image's history (nextHistoryLine)
30 $width, # \
31 $height, # |
32 $bits, # --- returned by getimagesize (loadFromXxx)
33 $type, # |
34 $attr, # /
35 $size, # Size in bytes (loadFromXxx)
36 $dataLoaded; # Whether or not all this has been loaded from the database (loadFromXxx)
37
38
39 /**#@-*/
40
41 /**
42 * Create an Image object from an image name
43 *
44 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
45 * @access public
46 */
47 function newFromName( $name ) {
48 $title = Title::makeTitleSafe( NS_IMAGE, $name );
49 return new Image( $title );
50 }
51
52 /**
53 * Obsolete factory function, use constructor
54 */
55 function newFromTitle( $title ) {
56 return new Image( $title );
57 }
58
59 function Image( $title ) {
60 $this->title =& $title;
61 $this->name = $title->getDBkey();
62
63 $n = strrpos( $this->name, '.' );
64 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
65 $this->historyLine = 0;
66
67 $this->dataLoaded = false;
68 }
69
70 /**
71 * Get the memcached keys
72 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
73 */
74 function getCacheKeys( $shared = false ) {
75 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
76
77 $foundCached = false;
78 $hashedName = md5($this->name);
79 $keys = array( "$wgDBname:Image:$hashedName" );
80 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
81 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
82 }
83 return $keys;
84 }
85
86 /**
87 * Try to load image metadata from memcached. Returns true on success.
88 */
89 function loadFromCache() {
90 global $wgUseSharedUploads, $wgMemc;
91 $fname = 'Image::loadFromMemcached';
92 wfProfileIn( $fname );
93 $this->dataLoaded = false;
94 $keys = $this->getCacheKeys();
95 $cachedValues = $wgMemc->get( $keys[0] );
96
97 // Check if the key existed and belongs to this version of MediaWiki
98 if (!empty($cachedValues) && is_array($cachedValues) && isset($cachedValues['width']) && $cachedValues['fileExists']) {
99 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
100 # if this is shared file, we need to check if image
101 # in shared repository has not changed
102 if ( isset( $keys[1] ) ) {
103 $commonsCachedValues = $wgMemc->get( $keys[1] );
104 if (!empty($commonsCachedValues) && is_array($commonsCachedValues) && isset($commonsCachedValues['width'])) {
105 $this->name = $commonsCachedValues['name'];
106 $this->imagePath = $commonsCachedValues['imagePath'];
107 $this->fileExists = $commonsCachedValues['fileExists'];
108 $this->width = $commonsCachedValues['width'];
109 $this->height = $commonsCachedValues['height'];
110 $this->bits = $commonsCachedValues['bits'];
111 $this->type = $commonsCachedValues['type'];
112 $this->size = $commonsCachedValues['size'];
113 $this->fromSharedDirectory = true;
114 $this->dataLoaded = true;
115 $this->imagePath = $this->getFullPath(true);
116 }
117 }
118 }
119 else {
120 $this->name = $cachedValues['name'];
121 $this->imagePath = $cachedValues['imagePath'];
122 $this->fileExists = $cachedValues['fileExists'];
123 $this->width = $cachedValues['width'];
124 $this->height = $cachedValues['height'];
125 $this->bits = $cachedValues['bits'];
126 $this->type = $cachedValues['type'];
127 $this->size = $cachedValues['size'];
128 $this->fromSharedDirectory = false;
129 $this->dataLoaded = true;
130 $this->imagePath = $this->getFullPath();
131 }
132 }
133
134 wfProfileOut( $fname );
135 return $this->dataLoaded;
136 }
137
138 /**
139 * Save the image metadata to memcached
140 */
141 function saveToCache() {
142 global $wgMemc;
143 $this->load();
144 // We can't cache metadata for non-existent files, because if the file later appears
145 // in commons, the local keys won't be purged.
146 if ( $this->fileExists ) {
147 $keys = $this->getCacheKeys();
148
149 $cachedValues = array('name' => $this->name,
150 'imagePath' => $this->imagePath,
151 'fileExists' => $this->fileExists,
152 'fromShared' => $this->fromSharedDirectory,
153 'width' => $this->width,
154 'height' => $this->height,
155 'bits' => $this->bits,
156 'type' => $this->type,
157 'size' => $this->size);
158
159 $wgMemc->set( $keys[0], $cachedValues );
160 }
161 }
162
163 /**
164 * Load metadata from the file itself
165 */
166 function loadFromFile() {
167 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgLang;
168 $fname = 'Image::loadFromFile';
169 wfProfileIn( $fname );
170 $this->imagePath = $this->getFullPath();
171 $this->fileExists = file_exists( $this->imagePath );
172 $this->fromSharedDirectory = false;
173 $gis = false;
174
175 # If the file is not found, and a shared upload directory is used, look for it there.
176 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
177 # In case we're on a wgCapitalLinks=false wiki, we
178 # capitalize the first letter of the filename before
179 # looking it up in the shared repository.
180 $sharedImage = Image::newFromName( $wgLang->ucfirst($this->name) );
181 $this->fileExists = file_exists( $sharedImage->getFullPath(true) );
182 if ( $this->fileExists ) {
183 $this->name = $sharedImage->name;
184 $this->imagePath = $this->getFullPath(true);
185 $this->fromSharedDirectory = true;
186 }
187 }
188
189 if ( $this->fileExists ) {
190 # Get size in bytes
191 $this->size = filesize( $this->imagePath );
192
193 # Height and width
194 # Don't try to get the width and height of sound and video files, that's bad for performance
195 if ( !Image::isKnownImageExtension( $this->extension ) ) {
196 $gis = false;
197 } elseif( $this->extension == 'svg' ) {
198 wfSuppressWarnings();
199 $gis = wfGetSVGsize( $this->imagePath );
200 wfRestoreWarnings();
201 } else {
202 wfSuppressWarnings();
203 $gis = getimagesize( $this->imagePath );
204 wfRestoreWarnings();
205 }
206 }
207 if( $gis === false ) {
208 $this->width = 0;
209 $this->height = 0;
210 $this->bits = 0;
211 $this->type = 0;
212 } else {
213 $this->width = $gis[0];
214 $this->height = $gis[1];
215 $this->type = $gis[2];
216 if ( isset( $gis['bits'] ) ) {
217 $this->bits = $gis['bits'];
218 } else {
219 $this->bits = 0;
220 }
221 }
222 $this->dataLoaded = true;
223 wfProfileOut( $fname );
224 }
225
226 /**
227 * Load image metadata from the DB
228 */
229 function loadFromDB() {
230 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgLang;
231 $fname = 'Image::loadFromDB';
232 wfProfileIn( $fname );
233
234 $dbr =& wfGetDB( DB_SLAVE );
235 $row = $dbr->selectRow( 'image',
236 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
237 array( 'img_name' => $this->name ), $fname );
238 if ( $row ) {
239 $this->fromSharedDirectory = false;
240 $this->fileExists = true;
241 $this->loadFromRow( $row );
242 $this->imagePath = $this->getFullPath();
243 // Check for rows from a previous schema, quietly upgrade them
244 if ( $this->type == -1 ) {
245 $this->upgradeRow();
246 }
247 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
248 # In case we're on a wgCapitalLinks=false wiki, we
249 # capitalize the first letter of the filename before
250 # looking it up in the shared repository.
251 $name = $wgLang->ucfirst($this->name);
252
253 $row = $dbr->selectRow( "`$wgSharedUploadDBname`.image",
254 array( 'img_size', 'img_width', 'img_height', 'img_bits', 'img_type' ),
255 array( 'img_name' => $name ), $fname );
256 if ( $row ) {
257 $this->fromSharedDirectory = true;
258 $this->fileExists = true;
259 $this->imagePath = $this->getFullPath(true);
260 $this->name = $name;
261 $this->loadFromRow( $row );
262
263 // Check for rows from a previous schema, quietly upgrade them
264 if ( $this->type == -1 ) {
265 $this->upgradeRow();
266 }
267 }
268 }
269
270 if ( !$row ) {
271 $this->size = 0;
272 $this->width = 0;
273 $this->height = 0;
274 $this->bits = 0;
275 $this->type = 0;
276 $this->fileExists = false;
277 $this->fromSharedDirectory = false;
278 }
279
280 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
281 $this->dataLoaded = true;
282 }
283
284 /*
285 * Load image metadata from a DB result row
286 */
287 function loadFromRow( &$row ) {
288 $this->size = $row->img_size;
289 $this->width = $row->img_width;
290 $this->height = $row->img_height;
291 $this->bits = $row->img_bits;
292 $this->type = $row->img_type;
293 $this->dataLoaded = true;
294 }
295
296 /**
297 * Load image metadata from cache or DB, unless already loaded
298 */
299 function load() {
300 global $wgSharedUploadDBname, $wgUseSharedUploads;
301 if ( !$this->dataLoaded ) {
302 if ( !$this->loadFromCache() ) {
303 $this->loadFromDB();
304 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
305 $this->loadFromFile();
306 } elseif ( $this->fileExists ) {
307 $this->saveToCache();
308 }
309 }
310 $this->dataLoaded = true;
311 }
312 }
313
314 /**
315 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
316 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
317 */
318 function upgradeRow() {
319 global $wgDBname, $wgSharedUploadDBname;
320 $fname = 'Image::upgradeRow';
321 $this->loadFromFile();
322 $dbw =& wfGetDB( DB_MASTER );
323
324 if ( $this->fromSharedDirectory ) {
325 if ( !$wgSharedUploadDBname ) {
326 return;
327 }
328
329 // Write to the other DB using selectDB, not database selectors
330 // This avoids breaking replication in MySQL
331 $dbw->selectDB( $wgSharedUploadDBname );
332 }
333 $dbw->update( '`image`',
334 array(
335 'img_width' => $this->width,
336 'img_height' => $this->height,
337 'img_bits' => $this->bits,
338 'img_type' => $this->type,
339 ), array( 'img_name' => $this->name ), $fname
340 );
341 if ( $this->fromSharedDirectory ) {
342 $dbw->selectDB( $wgDBname );
343 }
344 }
345
346 /**
347 * Return the name of this image
348 * @access public
349 */
350 function getName() {
351 return $this->name;
352 }
353
354 /**
355 * Return the associated title object
356 * @access public
357 */
358 function getTitle() {
359 return $this->title;
360 }
361
362 /**
363 * Return the URL of the image file
364 * @access public
365 */
366 function getURL() {
367 if ( !$this->url ) {
368 $this->load();
369 if($this->fileExists) {
370 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
371 } else {
372 $this->url = '';
373 }
374 }
375 return $this->url;
376 }
377
378 function getViewURL() {
379 if( $this->mustRender() ) {
380 return $this->createThumb( $this->getWidth() );
381 } else {
382 return $this->getURL();
383 }
384 }
385
386 /**
387 * Return the image path of the image in the
388 * local file system as an absolute path
389 * @access public
390 */
391 function getImagePath() {
392 $this->load();
393 return $this->imagePath;
394 }
395
396 /**
397 * Return the width of the image
398 *
399 * Returns -1 if the file specified is not a known image type
400 * @access public
401 */
402 function getWidth() {
403 $this->load();
404 return $this->width;
405 }
406
407 /**
408 * Return the height of the image
409 *
410 * Returns -1 if the file specified is not a known image type
411 * @access public
412 */
413 function getHeight() {
414 $this->load();
415 return $this->height;
416 }
417
418 /**
419 * Return the size of the image file, in bytes
420 * @access public
421 */
422 function getSize() {
423 $this->load();
424 return $this->size;
425 }
426
427 /**
428 * Return the type of the image
429 *
430 * - 1 GIF
431 * - 2 JPG
432 * - 3 PNG
433 * - 15 WBMP
434 * - 16 XBM
435 */
436 function getType() {
437 $this->load();
438 return $this->type;
439 }
440
441 /**
442 * Return the escapeLocalURL of this image
443 * @access public
444 */
445 function getEscapeLocalURL() {
446 $this->getTitle();
447 return $this->title->escapeLocalURL();
448 }
449
450 /**
451 * Return the escapeFullURL of this image
452 * @access public
453 */
454 function getEscapeFullURL() {
455 $this->getTitle();
456 return $this->title->escapeFullURL();
457 }
458
459 /**
460 * Return the URL of an image, provided its name.
461 *
462 * @param string $name Name of the image, without the leading "Image:"
463 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
464 * @access public
465 * @static
466 */
467 function imageUrl( $name, $fromSharedDirectory = false ) {
468 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
469 if($fromSharedDirectory) {
470 $base = '';
471 $path = $wgSharedUploadPath;
472 } else {
473 $base = $wgUploadBaseUrl;
474 $path = $wgUploadPath;
475 }
476 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
477 return wfUrlencode( $url );
478 }
479
480 /**
481 * Returns true if the image file exists on disk.
482 *
483 * @access public
484 */
485 function exists() {
486 $this->load();
487 return $this->fileExists;
488 }
489
490 /**
491 *
492 * @access private
493 */
494 function thumbUrl( $width, $subdir='thumb') {
495 global $wgUploadPath, $wgUploadBaseUrl,
496 $wgSharedUploadPath,$wgSharedUploadDirectory,
497 $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
498
499 // Generate thumb.php URL if possible
500 $script = false;
501 $url = false;
502
503 if ( $this->fromSharedDirectory ) {
504 if ( $wgSharedThumbnailScriptPath ) {
505 $script = $wgSharedThumbnailScriptPath;
506 }
507 } else {
508 if ( $wgThumbnailScriptPath ) {
509 $script = $wgThumbnailScriptPath;
510 }
511 }
512 if ( $script ) {
513 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
514 } else {
515 $name = $this->thumbName( $width );
516 if($this->fromSharedDirectory) {
517 $base = '';
518 $path = $wgSharedUploadPath;
519 } else {
520 $base = $wgUploadBaseUrl;
521 $path = $wgUploadPath;
522 }
523 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
524 $url = "{$base}{$path}/{$subdir}" .
525 wfGetHashPath($this->name, $this->fromSharedDirectory)
526 . $this->name.'/'.$name;
527 $url = wfUrlencode( $url );
528 } else {
529 $url = "{$base}{$path}/{$subdir}/{$name}";
530 }
531 }
532 return array( $script !== false, $url );
533 }
534
535 /**
536 * Return the file name of a thumbnail of the specified width
537 *
538 * @param integer $width Width of the thumbnail image
539 * @param boolean $shared Does the thumbnail come from the shared repository?
540 * @access private
541 */
542 function thumbName( $width ) {
543 $thumb = $width."px-".$this->name;
544 if( $this->extension == 'svg' ) {
545 # Rasterize SVG vector images to PNG
546 $thumb .= '.png';
547 }
548 return $thumb;
549 }
550
551 /**
552 * Create a thumbnail of the image having the specified width/height.
553 * The thumbnail will not be created if the width is larger than the
554 * image's width. Let the browser do the scaling in this case.
555 * The thumbnail is stored on disk and is only computed if the thumbnail
556 * file does not exist OR if it is older than the image.
557 * Returns the URL.
558 *
559 * Keeps aspect ratio of original image. If both width and height are
560 * specified, the generated image will be no bigger than width x height,
561 * and will also have correct aspect ratio.
562 *
563 * @param integer $width maximum width of the generated thumbnail
564 * @param integer $height maximum height of the image (optional)
565 * @access public
566 */
567 function createThumb( $width, $height=-1 ) {
568 $thumb = $this->getThumbnail( $width, $height );
569 if( is_null( $thumb ) ) return '';
570 return $thumb->getUrl();
571 }
572
573 /**
574 * As createThumb, but returns a ThumbnailImage object. This can
575 * provide access to the actual file, the real size of the thumb,
576 * and can produce a convenient <img> tag for you.
577 *
578 * @param integer $width maximum width of the generated thumbnail
579 * @param integer $height maximum height of the image (optional)
580 * @return ThumbnailImage
581 * @access public
582 */
583 function &getThumbnail( $width, $height=-1 ) {
584 if ( $height == -1 ) {
585 return $this->renderThumb( $width );
586 }
587 $this->load();
588 if ( $width < $this->width ) {
589 $thumbheight = $this->height * $width / $this->width;
590 $thumbwidth = $width;
591 } else {
592 $thumbheight = $this->height;
593 $thumbwidth = $this->width;
594 }
595 if ( $thumbheight > $height ) {
596 $thumbwidth = $thumbwidth * $height / $thumbheight;
597 $thumbheight = $height;
598 }
599 $thumb = $this->renderThumb( $thumbwidth );
600 if( is_null( $thumb ) ) {
601 $thumb = $this->iconThumb();
602 }
603 return $thumb;
604 }
605
606 /**
607 * @return ThumbnailImage
608 */
609 function iconThumb() {
610 global $wgStylePath, $wgStyleDirectory;
611
612 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
613 foreach( $try as $icon ) {
614 $path = '/common/images/' . $icon;
615 $filepath = $wgStyleDirectory . $path;
616 if( file_exists( $filepath ) ) {
617 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
618 }
619 }
620 return null;
621 }
622
623 /**
624 * Create a thumbnail of the image having the specified width.
625 * The thumbnail will not be created if the width is larger than the
626 * image's width. Let the browser do the scaling in this case.
627 * The thumbnail is stored on disk and is only computed if the thumbnail
628 * file does not exist OR if it is older than the image.
629 * Returns an object which can return the pathname, URL, and physical
630 * pixel size of the thumbnail -- or null on failure.
631 *
632 * @return ThumbnailImage
633 * @access private
634 */
635 function /* private */ renderThumb( $width, $useScript = true ) {
636 global $wgUseSquid, $wgInternalServer;
637 global $wgThumbnailScriptPath, $wgSharedThumbnailScriptPath;
638
639 $width = IntVal( $width );
640
641 $this->load();
642 if ( ! $this->exists() )
643 {
644 # If there is no image, there will be no thumbnail
645 return null;
646 }
647
648 # Sanity check $width
649 if( $width <= 0 ) {
650 # BZZZT
651 return null;
652 }
653
654 if( $width > $this->width && !$this->mustRender() ) {
655 # Don't make an image bigger than the source
656 return new ThumbnailImage( $this->getViewURL(), $this->getWidth(), $this->getHeight() );
657 }
658
659 $height = floor( $this->height * ( $width/$this->width ) );
660
661 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
662 if ( $isScriptUrl && $useScript ) {
663 // Use thumb.php to render the image
664 return new ThumbnailImage( $url, $width, $height );
665 }
666
667 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
668 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
669
670 if ( !file_exists( $thumbPath ) ) {
671 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
672 '/'.$thumbName;
673 $done = false;
674 if ( file_exists( $oldThumbPath ) ) {
675 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
676 rename( $oldThumbPath, $thumbPath );
677 $done = true;
678 } else {
679 unlink( $oldThumbPath );
680 }
681 }
682 if ( !$done ) {
683 $this->reallyRenderThumb( $thumbPath, $width, $height );
684
685 # Purge squid
686 # This has to be done after the image is updated and present for all machines on NFS,
687 # or else the old version might be stored into the squid again
688 if ( $wgUseSquid ) {
689 if ( substr( $url, 0, 4 ) == 'http' ) {
690 $urlArr = array( $url );
691 } else {
692 $urlArr = array( $wgInternalServer.$url );
693 }
694 wfPurgeSquidServers($urlArr);
695 }
696 }
697 }
698 return new ThumbnailImage( $url, $width, $height, $thumbPath );
699 } // END OF function renderThumb
700
701 /**
702 * Really render a thumbnail
703 *
704 * @access private
705 */
706 function /*private*/ reallyRenderThumb( $thumbPath, $width, $height ) {
707 global $wgSVGConverters, $wgSVGConverter,
708 $wgUseImageMagick, $wgImageMagickConvertCommand;
709
710 $this->load();
711
712 if( $this->extension == 'svg' ) {
713 global $wgSVGConverters, $wgSVGConverter;
714 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
715 global $wgSVGConverterPath;
716 $cmd = str_replace(
717 array( '$path/', '$width', '$input', '$output' ),
718 array( $wgSVGConverterPath,
719 $width,
720 escapeshellarg( $this->imagePath ),
721 escapeshellarg( $thumbPath ) ),
722 $wgSVGConverters[$wgSVGConverter] );
723 $conv = shell_exec( $cmd );
724 } else {
725 $conv = false;
726 }
727 } elseif ( $wgUseImageMagick ) {
728 # use ImageMagick
729 # Specify white background color, will be used for transparent images
730 # in Internet Explorer/Windows instead of default black.
731 $cmd = $wgImageMagickConvertCommand .
732 " -quality 85 -background white -geometry {$width} ".
733 escapeshellarg($this->imagePath) . " " .
734 escapeshellarg($thumbPath);
735 $conv = shell_exec( $cmd );
736 } else {
737 # Use PHP's builtin GD library functions.
738 #
739 # First find out what kind of file this is, and select the correct
740 # input routine for this.
741
742 $truecolor = false;
743
744 switch( $this->type ) {
745 case 1: # GIF
746 $src_image = imagecreatefromgif( $this->imagePath );
747 break;
748 case 2: # JPG
749 $src_image = imagecreatefromjpeg( $this->imagePath );
750 $truecolor = true;
751 break;
752 case 3: # PNG
753 $src_image = imagecreatefrompng( $this->imagePath );
754 $truecolor = ( $this->bits > 8 );
755 break;
756 case 15: # WBMP for WML
757 $src_image = imagecreatefromwbmp( $this->imagePath );
758 break;
759 case 16: # XBM
760 $src_image = imagecreatefromxbm( $this->imagePath );
761 break;
762 default:
763 return 'Image type not supported';
764 break;
765 }
766 if ( $truecolor ) {
767 $dst_image = imagecreatetruecolor( $width, $height );
768 } else {
769 $dst_image = imagecreate( $width, $height );
770 }
771 imagecopyresampled( $dst_image, $src_image,
772 0,0,0,0,
773 $width, $height, $this->width, $this->height );
774 switch( $this->type ) {
775 case 1: # GIF
776 case 3: # PNG
777 case 15: # WBMP
778 case 16: # XBM
779 imagepng( $dst_image, $thumbPath );
780 break;
781 case 2: # JPEG
782 imageinterlace( $dst_image );
783 imagejpeg( $dst_image, $thumbPath, 95 );
784 break;
785 default:
786 break;
787 }
788 imagedestroy( $dst_image );
789 imagedestroy( $src_image );
790 }
791 #
792 # Check for zero-sized thumbnails. Those can be generated when
793 # no disk space is available or some other error occurs
794 #
795 if( file_exists( $thumbPath ) ) {
796 $thumbstat = stat( $thumbPath );
797 if( $thumbstat['size'] == 0 ) {
798 unlink( $thumbPath );
799 }
800 }
801 }
802
803 /**
804 * Get all thumbnail names previously generated for this image
805 */
806 function getThumbnails( $shared = false ) {
807 if ( Image::isHashed( $shared ) ) {
808 $this->load();
809 $files = array();
810 $dir = wfImageThumbDir( $this->name, $shared );
811
812 // This generates an error on failure, hence the @
813 $handle = @opendir( $dir );
814
815 if ( $handle ) {
816 while ( false !== ( $file = readdir($handle) ) ) {
817 if ( $file{0} != '.' ) {
818 $files[] = $file;
819 }
820 }
821 closedir( $handle );
822 }
823 } else {
824 $files = array();
825 }
826
827 return $files;
828 }
829
830 /**
831 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
832 */
833 function purgeCache( $archiveFiles = array(), $shared = false ) {
834 global $wgInternalServer, $wgUseSquid;
835
836 // Refresh metadata cache
837 clearstatcache();
838 $this->loadFromFile();
839 $this->saveToCache();
840
841 // Delete thumbnails
842 $files = $this->getThumbnails( $shared );
843 $dir = wfImageThumbDir( $this->name, $shared );
844 $urls = array();
845 foreach ( $files as $file ) {
846 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
847 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
848 @unlink( "$dir/$file" );
849 }
850 }
851
852 // Purge the squid
853 if ( $wgUseSquid ) {
854 $urls[] = $wgInternalServer . $this->getViewURL();
855 foreach ( $archiveFiles as $file ) {
856 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
857 }
858 wfPurgeSquidServers( $urls );
859 }
860 }
861
862 /**
863 * Return the image history of this image, line by line.
864 * starts with current version, then old versions.
865 * uses $this->historyLine to check which line to return:
866 * 0 return line for current version
867 * 1 query for old versions, return first one
868 * 2, ... return next old version from above query
869 *
870 * @access public
871 */
872 function nextHistoryLine() {
873 $fname = 'Image::nextHistoryLine()';
874 $dbr =& wfGetDB( DB_SLAVE );
875 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
876 $this->historyRes = $dbr->select( 'image',
877 array( 'img_size','img_description','img_user','img_user_text','img_timestamp', "'' AS oi_archive_name" ),
878 array( 'img_name' => $this->title->getDBkey() ),
879 $fname
880 );
881 if ( 0 == wfNumRows( $this->historyRes ) ) {
882 return FALSE;
883 }
884 } else if ( $this->historyLine == 1 ) {
885 $this->historyRes = $dbr->select( 'oldimage',
886 array( 'oi_size AS img_size', 'oi_description AS img_description', 'oi_user AS img_user',
887 'oi_user_text AS img_user_text', 'oi_timestamp AS img_timestamp', 'oi_archive_name'
888 ), array( 'oi_name' => $this->title->getDBkey() ), $fname, array( 'ORDER BY' => 'oi_timestamp DESC' )
889 );
890 }
891 $this->historyLine ++;
892
893 return $dbr->fetchObject( $this->historyRes );
894 }
895
896 /**
897 * Reset the history pointer to the first element of the history
898 * @access public
899 */
900 function resetHistory() {
901 $this->historyLine = 0;
902 }
903
904 /**
905 * Return true if the file is of a type that can't be directly
906 * rendered by typical browsers and needs to be re-rasterized.
907 * @return bool
908 */
909 function mustRender() {
910 $this->load();
911 return ( $this->extension == 'svg' );
912 }
913
914 /**
915 * Return the full filesystem path to the file. Note that this does
916 * not mean that a file actually exists under that location.
917 *
918 * This path depends on whether directory hashing is active or not,
919 * i.e. whether the images are all found in the same directory,
920 * or in hashed paths like /images/3/3c.
921 *
922 * @access public
923 * @param boolean $fromSharedDirectory Return the path to the file
924 * in a shared repository (see $wgUseSharedRepository and related
925 * options in DefaultSettings.php) instead of a local one.
926 *
927 */
928 function getFullPath( $fromSharedRepository = false ) {
929 global $wgUploadDirectory, $wgSharedUploadDirectory;
930 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
931
932 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
933 $wgUploadDirectory;
934
935 // $wgSharedUploadDirectory may be false, if thumb.php is used
936 if ( $dir ) {
937 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
938 } else {
939 $fullpath = false;
940 }
941
942 return $fullpath;
943 }
944
945 /**
946 * @return bool
947 * @static
948 */
949 function isHashed( $shared ) {
950 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
951 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
952 }
953
954 /**
955 * @return bool
956 * @static
957 */
958 function isKnownImageExtension( $ext ) {
959 static $extensions = array( 'svg', 'png', 'jpg', 'jpeg', 'gif', 'bmp', 'xbm' );
960 return in_array( $ext, $extensions );
961 }
962
963 /**
964 * Record an image upload in the upload log and the image table
965 */
966 function recordUpload( $oldver, $desc, $copyStatus = '', $source = '' ) {
967 global $wgUser, $wgLang, $wgTitle, $wgOut, $wgDeferredUpdateList;
968 global $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
969
970 $fname = 'Image::recordUpload';
971 $dbw =& wfGetDB( DB_MASTER );
972
973 # img_name must be unique
974 if ( !$dbw->indexUnique( 'image', 'img_name' ) && !$dbw->indexExists('image','PRIMARY') ) {
975 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
976 }
977
978 // Delete thumbnails and refresh the metadata cache
979 $this->purgeCache();
980
981 // Fail now if the image isn't there
982 if ( !$this->fileExists || $this->fromSharedDirectory ) {
983 return false;
984 }
985
986 if ( $wgUseCopyrightUpload ) {
987 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
988 '== ' . wfMsg ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
989 '== ' . wfMsg ( 'filesource' ) . " ==\n" . $source ;
990 } else {
991 $textdesc = $desc;
992 }
993
994 $now = $dbw->timestamp();
995
996 # Test to see if the row exists using INSERT IGNORE
997 # This avoids race conditions by locking the row until the commit, and also
998 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
999 $dbw->insert( 'image',
1000 array(
1001 'img_name' => $this->name,
1002 'img_size'=> $this->size,
1003 'img_width' => $this->width,
1004 'img_height' => $this->height,
1005 'img_bits' => $this->bits,
1006 'img_type' => $this->type,
1007 'img_timestamp' => $now,
1008 'img_description' => $desc,
1009 'img_user' => $wgUser->getID(),
1010 'img_user_text' => $wgUser->getName(),
1011 ), $fname, 'IGNORE'
1012 );
1013 $descTitle = $this->getTitle();
1014 $purgeURLs = array();
1015
1016 if ( $dbw->affectedRows() ) {
1017 # Successfully inserted, this is a new image
1018 $id = $descTitle->getArticleID();
1019
1020 if ( $id == 0 ) {
1021 $article = new Article( $descTitle );
1022 $article->insertNewArticle( $textdesc, $desc, false, false, true );
1023 }
1024 } else {
1025 # Collision, this is an update of an image
1026 # Insert previous contents into oldimage
1027 $dbw->insertSelect( 'oldimage', 'image',
1028 array(
1029 'oi_name' => 'img_name',
1030 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1031 'oi_size' => 'img_size',
1032 'oi_width' => 'img_width',
1033 'oi_height' => 'img_height',
1034 'oi_bits' => 'img_bits',
1035 'oi_type' => 'img_type',
1036 'oi_timestamp' => 'img_timestamp',
1037 'oi_description' => 'img_description',
1038 'oi_user' => 'img_user',
1039 'oi_user_text' => 'img_user_text',
1040 ), array( 'img_name' => $this->name ), $fname
1041 );
1042
1043 # Update the current image row
1044 $dbw->update( 'image',
1045 array( /* SET */
1046 'img_size' => $this->size,
1047 'img_width' => $this->width,
1048 'img_height' => $this->height,
1049 'img_bits' => $this->bits,
1050 'img_type' => $this->type,
1051 'img_timestamp' => $now,
1052 'img_user' => $wgUser->getID(),
1053 'img_user_text' => $wgUser->getName(),
1054 'img_description' => $desc,
1055 ), array( /* WHERE */
1056 'img_name' => $this->name
1057 ), $fname
1058 );
1059
1060 # Invalidate the cache for the description page
1061 $descTitle->invalidateCache();
1062 $purgeURLs[] = $descTitle->getInternalURL();
1063 }
1064
1065 # Invalidate cache for all pages using this image
1066 $linksTo = $this->getLinksTo();
1067
1068 if ( $wgUseSquid ) {
1069 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1070 array_push( $wgPostCommitUpdateList, $u );
1071 }
1072 Title::touchArray( $linksTo );
1073
1074 $log = new LogPage( 'upload' );
1075 $log->addEntry( 'upload', $descTitle, $desc );
1076
1077 return true;
1078 }
1079
1080 /**
1081 * Get an array of Title objects which are articles which use this image
1082 * Also adds their IDs to the link cache
1083 *
1084 * This is mostly copied from Title::getLinksTo()
1085 */
1086 function getLinksTo( $options = '' ) {
1087 global $wgLinkCache;
1088 $fname = 'Image::getLinksTo';
1089 wfProfileIn( $fname );
1090
1091 if ( $options ) {
1092 $db =& wfGetDB( DB_MASTER );
1093 } else {
1094 $db =& wfGetDB( DB_SLAVE );
1095 }
1096
1097 extract( $db->tableNames( 'page', 'imagelinks' ) );
1098 $encName = $db->addQuotes( $this->name );
1099 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1100 $res = $db->query( $sql, $fname );
1101
1102 $retVal = array();
1103 if ( $db->numRows( $res ) ) {
1104 while ( $row = $db->fetchObject( $res ) ) {
1105 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1106 $wgLinkCache->addGoodLink( $row->page_id, $titleObj->getPrefixedDBkey() );
1107 $retVal[] = $titleObj;
1108 }
1109 }
1110 }
1111 $db->freeResult( $res );
1112 return $retVal;
1113 }
1114
1115 function retrieveExifData () {
1116 global $wgShowEXIF ;
1117 if ( ! $wgShowEXIF ) return array () ;
1118
1119 $file = $this->getImagePath () ;
1120 $per = new phpExifReader ( $file ) ;
1121 $per->processFile () ;
1122 $a = $per->getImageInfo() ;
1123 unset ( $a["FileName"] ) ;
1124 unset ( $a["Thumbnail"] ) ;
1125 return $a ;
1126 }
1127
1128 function getExifData () {
1129 return $this->retrieveExifData () ;
1130 }
1131
1132 function storeExifData () {
1133 }
1134
1135 } //class
1136
1137
1138 /**
1139 * Returns the image directory of an image
1140 * If the directory does not exist, it is created.
1141 * The result is an absolute path.
1142 *
1143 * This function is called from thumb.php before Setup.php is included
1144 *
1145 * @param string $fname file name of the image file
1146 * @access public
1147 */
1148 function wfImageDir( $fname ) {
1149 global $wgUploadDirectory, $wgHashedUploadDirectory;
1150
1151 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1152
1153 $hash = md5( $fname );
1154 $oldumask = umask(0);
1155 $dest = $wgUploadDirectory . '/' . $hash{0};
1156 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1157 $dest .= '/' . substr( $hash, 0, 2 );
1158 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1159
1160 umask( $oldumask );
1161 return $dest;
1162 }
1163
1164 /**
1165 * Returns the image directory of an image's thubnail
1166 * If the directory does not exist, it is created.
1167 * The result is an absolute path.
1168 *
1169 * This function is called from thumb.php before Setup.php is included
1170 *
1171 * @param string $fname file name of the original image file
1172 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the thumbnail. Default is 'thumb'
1173 * @param boolean $shared (optional) use the shared upload directory
1174 * @access public
1175 */
1176 function wfImageThumbDir( $fname, $shared = false ) {
1177 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1178 if ( Image::isHashed( $shared ) ) {
1179 $dir = "$base/$fname";
1180
1181 if ( !is_dir( $base ) ) {
1182 $oldumask = umask(0);
1183 @mkdir( $base, 0777 );
1184 umask( $oldumask );
1185 }
1186
1187 if ( ! is_dir( $dir ) ) {
1188 $oldumask = umask(0);
1189 @mkdir( $dir, 0777 );
1190 umask( $oldumask );
1191 }
1192 } else {
1193 $dir = $base;
1194 }
1195
1196 return $dir;
1197 }
1198
1199 /**
1200 * Old thumbnail directory, kept for conversion
1201 */
1202 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1203 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1204 }
1205
1206 /**
1207 * Returns the image directory of an image's old version
1208 * If the directory does not exist, it is created.
1209 * The result is an absolute path.
1210 *
1211 * This function is called from thumb.php before Setup.php is included
1212 *
1213 * @param string $fname file name of the thumbnail file, including file size prefix
1214 * @param string $subdir (optional) subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'
1215 * @param boolean $shared (optional) use the shared upload directory (only relevant for other functions which call this one)
1216 * @access public
1217 */
1218 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1219 global $wgUploadDirectory, $wgHashedUploadDirectory,
1220 $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1221 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1222 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1223 if (!$hashdir) { return $dir.'/'.$subdir; }
1224 $hash = md5( $fname );
1225 $oldumask = umask(0);
1226
1227 # Suppress warning messages here; if the file itself can't
1228 # be written we'll worry about it then.
1229 wfSuppressWarnings();
1230
1231 $archive = $dir.'/'.$subdir;
1232 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1233 $archive .= '/' . $hash{0};
1234 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1235 $archive .= '/' . substr( $hash, 0, 2 );
1236 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1237
1238 wfRestoreWarnings();
1239 umask( $oldumask );
1240 return $archive;
1241 }
1242
1243
1244 /*
1245 * Return the hash path component of an image path (URL or filesystem),
1246 * e.g. "/3/3c/", or just "/" if hashing is not used.
1247 *
1248 * @param $dbkey The filesystem / database name of the file
1249 * @param $fromSharedDirectory Use the shared file repository? It may
1250 * use different hash settings from the local one.
1251 */
1252 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1253 global $wgHashedSharedUploadDirectory, $wgSharedUploadDirectory;
1254 global $wgHashedUploadDirectory;
1255
1256 if( Image::isHashed( $fromSharedDirectory ) ) {
1257 $hash = md5($dbkey);
1258 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1259 } else {
1260 return '/';
1261 }
1262 }
1263
1264 /**
1265 * Returns the image URL of an image's old version
1266 *
1267 * @param string $fname file name of the image file
1268 * @param string $subdir (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1269 * @access public
1270 */
1271 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1272 global $wgUploadPath, $wgHashedUploadDirectory;
1273
1274 if ($wgHashedUploadDirectory) {
1275 $hash = md5( substr( $name, 15) );
1276 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1277 substr( $hash, 0, 2 ) . '/'.$name;
1278 } else {
1279 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1280 }
1281 return wfUrlencode($url);
1282 }
1283
1284 /**
1285 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1286 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1287 *
1288 * @param string $length
1289 * @return int Length in pixels
1290 */
1291 function wfScaleSVGUnit( $length ) {
1292 static $unitLength = array(
1293 'px' => 1.0,
1294 'pt' => 1.25,
1295 'pc' => 15.0,
1296 'mm' => 3.543307,
1297 'cm' => 35.43307,
1298 'in' => 90.0,
1299 '' => 1.0, // "User units" pixels by default
1300 '%' => 2.0, // Fake it!
1301 );
1302 if( preg_match( '/^(\d+)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1303 $length = FloatVal( $matches[1] );
1304 $unit = $matches[2];
1305 return round( $length * $unitLength[$unit] );
1306 } else {
1307 // Assume pixels
1308 return round( FloatVal( $length ) );
1309 }
1310 }
1311
1312 /**
1313 * Compatible with PHP getimagesize()
1314 * @todo support gzipped SVGZ
1315 * @todo check XML more carefully
1316 * @todo sensible defaults
1317 *
1318 * @param string $filename
1319 * @return array
1320 */
1321 function wfGetSVGsize( $filename ) {
1322 $width = 256;
1323 $height = 256;
1324
1325 // Read a chunk of the file
1326 $f = fopen( $filename, "rt" );
1327 if( !$f ) return false;
1328 $chunk = fread( $f, 4096 );
1329 fclose( $f );
1330
1331 // Uber-crappy hack! Run through a real XML parser.
1332 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1333 return false;
1334 }
1335 $tag = $matches[1];
1336 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1337 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1338 }
1339 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1340 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1341 }
1342
1343 return array( $width, $height, 'SVG',
1344 "width=\"$width\" height=\"$height\"" );
1345 }
1346
1347 /**
1348 * Is an image on the bad image list?
1349 */
1350 function wfIsBadImage( $name ) {
1351 global $wgLang;
1352
1353 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1354 foreach ( $lines as $line ) {
1355 if ( preg_match( '/^\*\s*\[\[:(' . $wgLang->getNsText( NS_IMAGE ) . ':.*(?=]]))\]\]/', $line, $m ) ) {
1356 $t = Title::newFromText( $m[1] );
1357 if ( $t->getDBkey() == $name ) {
1358 return true;
1359 }
1360 }
1361 }
1362 return false;
1363 }
1364
1365
1366
1367 /**
1368 * Wrapper class for thumbnail images
1369 * @package MediaWiki
1370 */
1371 class ThumbnailImage {
1372 /**
1373 * @param string $path Filesystem path to the thumb
1374 * @param string $url URL path to the thumb
1375 * @access private
1376 */
1377 function ThumbnailImage( $url, $width, $height, $path = false ) {
1378 $this->url = $url;
1379 $this->width = $width;
1380 $this->height = $height;
1381 $this->path = $path;
1382 }
1383
1384 /**
1385 * @return string The thumbnail URL
1386 */
1387 function getUrl() {
1388 return $this->url;
1389 }
1390
1391 /**
1392 * Return HTML <img ... /> tag for the thumbnail, will include
1393 * width and height attributes and a blank alt text (as required).
1394 *
1395 * You can set or override additional attributes by passing an
1396 * associative array of name => data pairs. The data will be escaped
1397 * for HTML output, so should be in plaintext.
1398 *
1399 * @param array $attribs
1400 * @return string
1401 * @access public
1402 */
1403 function toHtml( $attribs = array() ) {
1404 $attribs['src'] = $this->url;
1405 $attribs['width'] = $this->width;
1406 $attribs['height'] = $this->height;
1407 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1408
1409 $html = '<img ';
1410 foreach( $attribs as $name => $data ) {
1411 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1412 }
1413 $html .= '/>';
1414 return $html;
1415 }
1416
1417 }
1418 ?>